package com.poetry.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.poetry.constant.RedisConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@RequiredArgsConstructor
public class RedisUtil {
    private final StringRedisTemplate stringRedisTemplate;
    public void set(String key, Object value, Long expire, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), expire, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, Long expire, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(expire)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                          Function<ID, R> dbFallback, Long expire,  TimeUnit timeUnit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            // 缓存中存在直接返回
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            // 命中空值
            return null;
        }
        R r = dbFallback.apply(id);
        if (r == null) {
            //不存在于redis中写入空值
            stringRedisTemplate.opsForValue().set(key, "", RedisConstant.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, expire, timeUnit);
        return r;
    }

    public LocalDateTime getLastSyncTime() {
        String json = stringRedisTemplate.opsForValue().get(RedisConstant.LAST_POEM_SYNC);
        if (json == null) return null;

        try {
            // 使用 Jackson 解析 JSON
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Integer> dateMap = mapper.readValue(json, new TypeReference<Map<String, Integer>>() {});

            return LocalDateTime.of(
                    dateMap.get("year"),
                    dateMap.get("month"),
                    dateMap.get("day"),
                    dateMap.get("hour"),
                    dateMap.get("minute"),
                    dateMap.get("second")
            );
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse sync time", e);
        }
    }

    public void updateSyncTime( LocalDateTime localDateTime) {
        stringRedisTemplate.opsForValue().set(RedisConstant.LAST_POEM_SYNC, JSONUtil.toJsonStr(localDateTime));
    }

}
